package com.example.demo.utils;

import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.core.io.FileSystemResource;

import java.io.*;


/**
 * @author 幻
 * @date 2021-04-19 19:48
 */
public class ImgUtil {
    /**
     * 保存图片
     *
     * @param fileName 文件名
     * @param imgStr   图片字符串
     * @param path     文件保存路径
     * @return 是否保存成功
     */
    public static boolean saveImg(String fileName, String imgStr, String path) {
        Base64 base64 = new Base64();


        try {
            File tempFile = new File(path + "/" + fileName);
            byte[] bytes = base64.decode(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }

            //如果文件夹不存在,则创建文件夹
            if (!tempFile.getParentFile().exists()) {
                tempFile.getParentFile().mkdirs();
            } else {
                FileSystemResource fileSystemResource = new FileSystemResource(tempFile);
                String osUri = fileSystemResource.getURI().toString();
                System.out.println("osPath:" + osUri);

            }


            //保存图片
            OutputStream fileOutputStream = new FileOutputStream(tempFile);
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
            fileOutputStream.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将图片转成base64字符串
     *
     * @param imgPath 图片路径
     * @return 图片的base64 字符串
     */
    public static String getImgStr(String imgPath) {
        Base64 base64 = new Base64();
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(base64.encode(data));
    }

    /**
     * 测试getImgStr
     *
     * @param args
     */
    public static void main(String[] args) {
        String imgStr = getImgStr("C:\\Users\\11237\\Desktop\\2.jpg");
        System.out.println(imgStr);
        saveImg("test.jpg", imgStr, "D:\\user_images");
    }

}
